package com.nlx.notes.module.service.impl.user;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nlx.notes.configuer.redis.annotation.RedisLock;
import com.nlx.notes.module.bean.vo.wx.JSCodeVO;
import com.nlx.notes.module.core.enums.error.UserCodeEnum;
import com.nlx.notes.module.core.generator.IdGenerator;
import com.nlx.notes.module.core.util.JSONUtils;
import com.nlx.notes.module.entity.UserUniqueCodeRel;
import com.nlx.notes.module.mapper.UserUniqueCodeRelMapper;
import com.nlx.notes.module.service.user.IUserUniqueCodeRelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nlx.notes.support.handler.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author nlx
 * @since 2025-08-16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserUniqueCodeRelServiceImpl extends ServiceImpl<UserUniqueCodeRelMapper, UserUniqueCodeRel> implements IUserUniqueCodeRelService {

    private static final String WX_APP_ID = "wxb96354966351ea78";
    private static final String WX_APP_SECRET = "d3ea74a468181cb08bd7e0ba69521f5b";

    private static  String WX_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?appid="+WX_APP_ID+"&secret="+WX_APP_SECRET+"&js_code={wxCode}&grant_type=authorization_code";


    @Override
    @RedisLock(key = " 'user_code_init:' + #deviceCode")
    public String findUserCode(String deviceCode) {
        if(StrUtil.isEmpty(deviceCode)){
            return null;
        }
        String url = WX_OPENID_URL.replace("{wxCode}", deviceCode);
        log.info("调用url：{}",url);
        //前往微信获取openId
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        JsonNode body = JSONUtils.parse(response.getBody(),JsonNode.class);
        log.info("微信响应结果：{}", body);
        if(null == body){
            log.error("调用微信获取openId错误");
            return null;
        }
        String openId;
        if(body.get("openid") != null){
            openId = body.get("openid").asText();
        }else{
            log.error("调用微信获取openId错误");
            throw new BusinessException(UserCodeEnum.WX_OPENID_GET_ERROR);
        }
        // 判断当前客户端唯一标识是否已经绑定了用户
        String userCode = this.getBaseMapper().findUserCodeByClientCode(openId);
        if(StrUtil.isEmpty(userCode)){
            userCode = initUserCode(openId);
        }
        return userCode;
    }

    /**
     * 初始化用户唯一标识
     * @param deviceCode 客户端标识
     * @return String
     */
    private String initUserCode(String deviceCode) {
        UserUniqueCodeRel userUniqueCodeRel = new UserUniqueCodeRel();
        userUniqueCodeRel.setUserCode(IdGenerator.generateOrderId());
        userUniqueCodeRel.setClientCode(deviceCode);
        userUniqueCodeRel.setCreatedTime(LocalDateTime.now());
        userUniqueCodeRel.setDelFlag(0);
        this.save(userUniqueCodeRel);
        return userUniqueCodeRel.getUserCode();
    }
}
